package com.pcbly.web.components.email;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.pcbly.web.bean.mail.UserMailBean;
import com.pcbly.web.bean.mail.UserSendMainBean;

public class MailSend {

	private UserMailBean bean;
	private UserSendMainBean sendBean;

	public MailSend() {

	}
	private String getFromEmail() {
		String email = "";
		if (bean.getUserName().indexOf("@") > 0) {
			return bean.getUserName();
		} else {
			email = bean.getUserName();
			email = email + "@";
			String hostname = bean.getSmtpHostName();
			hostname = hostname.substring(hostname.indexOf(".") + 1, hostname
					.length());
			return email + "" + hostname;
		}
	}

	private Multipart getHtmlMultipart() throws Exception {
		BodyPart bodyPart = new MimeBodyPart();
		bodyPart.setContent(sendBean.getContext(), "text/html;charset=utf-8");
		Multipart mmp = new MimeMultipart();
		mmp.addBodyPart(bodyPart);
		MimeBodyPart mbp2 = new MimeBodyPart();
		if ("1".equals(sendBean.getIsAttach())) {
			mbp2.attachFile(sendBean.getAttachPath());
			mmp.addBodyPart(mbp2);
		}
		return mmp;
	}

	private Multipart getMultipart() throws Exception {
		BodyPart mbp1 = new MimeBodyPart();
		mbp1.setText(sendBean.getContext());
		MimeBodyPart mbp2 = new MimeBodyPart();

		Multipart mp = new MimeMultipart();
		mp.addBodyPart(mbp1);
		if ("1".equals(sendBean.getIsAttach())) {
			mbp2.attachFile(sendBean.getAttachPath());
			mp.addBodyPart(mbp2);
		}
		return mp;
	}

	private void getSendTo(MimeMessage message) throws Exception {
		String[] to = sendBean.getSendTo();
		if (to != null && to.length > 0) {
			InternetAddress[] addressTo = new InternetAddress[to.length];
			for (int i = 0; i < to.length; i++) {
				addressTo[i] = new InternetAddress(to[i]);
			}
			message.setRecipients(Message.RecipientType.TO, addressTo);
		}
	}

	private void getSendCC(MimeMessage message) throws Exception {
		String[] cc = sendBean.getSendCC();
		if (cc != null && cc.length > 0) {
			InternetAddress[] addressTo = new InternetAddress[cc.length];
			for (int i = 0; i < cc.length; i++) {
				addressTo[i] = new InternetAddress(cc[i]);
			}
			message.setRecipients(Message.RecipientType.CC, addressTo);
		}
	}

	private void getSendBCC(MimeMessage message) throws Exception {
		String[] bcc = sendBean.getSendBCC();
		if (bcc != null && bcc.length > 0) {
			InternetAddress[] addressTo = new InternetAddress[bcc.length];
			for (int i = 0; i < bcc.length; i++) {
				addressTo[i] = new InternetAddress(bcc[i]);
			}
			message.setRecipients(Message.RecipientType.BCC, addressTo);
		}
	}
	public MimeMessage getMimeMessage() throws Exception {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", bean.getSmtpHostName()); 
		props.put("mail.smtp.auth", "true");
		if (bean.getSmtpSSL().equals("1")) {
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.setProperty("mail.smtp.socketFactory.port", "" + bean.getSmtpPort()); 
			props.setProperty("mail.smtp.socketFactory.fallback", "false"); 
			props.setProperty("mail.quitwait", "false");
		}else{
			props.setProperty("mail.smtp.port", "" + bean.getSmtpPort());
		}
		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(bean.getUserName(),
								bean.getPassword());
					}
				});
		return new MimeMessage(session);

	} 
	private void sendMainEmail() throws Exception { 
		MimeMessage message = getMimeMessage();
		message.setFrom(new InternetAddress(getFromEmail()));
		sendBean.setTitle(MimeUtility.encodeText(new String(sendBean
				.getTitle().getBytes(), "utf-8"), "utf-8", "B"));
		message.setSubject(sendBean.getTitle());
		if ("1".equals(sendBean.getIsHTML())) {// check and send HTML 
			message.setContent(getHtmlMultipart());
		} else {
			message.setContent(getMultipart());
		}
		getSendTo(message);// send to
		getSendCC(message);// send cc
		getSendBCC(message);// send bcc
		message.setSentDate(new Date()); 
		Transport.send(message);
		if(message!=null){
			message=null;
		}
	}
	public void sendMail() throws Exception { 
		sendMainEmail();
	}

	public void setBean(UserMailBean bean) {
		this.bean = bean;
	}

	public UserMailBean getBean() {
		return bean;
	}

	public void setSendBean(UserSendMainBean sendBean) {
		this.sendBean = sendBean;
	}

	public UserSendMainBean getSendBean() {
		return sendBean;
	}

	
	public static void main(String[] args){
		MailSend send=new MailSend();
		UserMailBean mailBean=new UserMailBean(); 
		mailBean.setSmtpPort(25);
		mailBean.setSmtpSSL("0");
//		mailBean.setSmtpHostName("smtp.gmail.com");
//		mailBean.setSmtpHostName("smtp.qq.com");
		mailBean.setSmtpHostName("smtp.qq.com");
		//
		mailBean.setUserName("23258759@qq.com");
		mailBean.setPassword("tsgm15024179");
		send.setBean(mailBean);
		UserSendMainBean sendBean=new UserSendMainBean();
		sendBean.setContext("要设置 Outlook 2007 客户端处理 Gmail，请按以下步骤操作要设置 Outlook 2007 客户端处理 Gmail，请按以下步骤操作");
		sendBean.setTitle("要设置 Outlook 2007 客户端处理 Gmail，请按以下步骤操作");
		String[] ars={"pxjianke@gmail.com","pxjianke@hotmail.com"};
		sendBean.setSendTo(ars);
		send.setSendBean(sendBean);
		try{
		send.sendMail();
		System.out.println("send mail ok!");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
